/**
 * Author: ling
 * Create Time: 2018-12-04 10:08
 * Description: 命令模式
 */

setCommand = function (button, command) {
  button.onclick = function () {
    command.execute();
  }
};
MenuBar = {
  refresh: function() {
    console.log('刷新子菜单')
  }
};
SubMenu = {
  add: function() {
    console.log('增加子菜单')
  },
  del: function() {
    console.log('删除子菜单')
  }
};
RefreshMenuBarCommand = function(receiver) {
  this.receiver = receiver
};
RefreshMenuBarCommand.prototype.execute = function () {
  this.receiver.refresh();
};
AddSubMenuCommand = function (receiver) {
  this.receiver = receiver
};
AddSubMenuCommand.prototype.execute = function () {
  this.receiver.add()
};
DelSubMenuCommand = function(receiver) {
  this.receiver = receiver
};
DelSubMenuCommand.prototype.execute = function () {
  this.receiver.del()
};

refreshMenuBarCommand = new RefreshMenuBarCommand(MenuBar);
addSubMenuCommand = new AddSubMenuCommand(SubMenu);
delSubMenuCommand = new DelSubMenuCommand(SubMenu);
setCommand("按钮1", refreshMenuBarCommand);
setCommand("按钮2", addSubMenuCommand);
setCommand("按钮3", delSubMenuCommand);

// js可以写成
DelSubMenuCommand = function (receiver) {
  return function () {
    receiver.del()
  }
};

MoveCommand = function(receiver, pos) {
  this.receiver = receiver;
  this.pos = pos;
  this.oldPos = null;
};
MoveCommand.prototype.execute = function() {
  this.receiver.start('left', this.pos, 1000, 'strongEaseOut');
  // 记录小球开始移动前的位置
  this.oldPos = this.receiver.dom.getBoundingClientRect()[this.receiver.propertyName];
};
MoveCommand.prototype.undo = function(){
  // 回到小球移动前记录的位置
  this.receiver.start('left', this.oldPos, 1000, 'strongEaseOut');
};

Ryu = {
  attack: function() {
    console.log('攻击');
  },
  defense: function() {
    console.log('防御');
  },
  jump: function() {
    console.log('跳跃');
  },
  crouch: function() {
    console.log('蹲下');
  }
};
makeCommand = function (receiver, state) {
  return function () {
    receiver[state]
  }
};
commands = {
  "119": "jump", // W
  "115": "crouch", // S
  "97": "defense", // A
  "100": "attack" // D
};
commandStack = []; // 保存命令
document.onkeypress = function( ev ) {
  let keyCode = ev.keyCode,
    command = makeCommand( Ryu, commands[ keyCode ] );
  if (command) {
    // 执行命令
    command();
    commandStack.push(command); // 将刚刚执行过的命令保存进堆栈
  }
};
// 播放录像
replay = function () {
  for(let command of commandStack) {
    command()
  }
};

closeDoorCommand = {
 execute: function () {
   console.log('关门')
 }
};
openPCCommand = {
  execute: function () {
    console.log('打开电脑')
  }
};
openQQCommand = {
  execute: function () {
    console.log('打开QQ')
  }
};
MarcoCommand = function () {
  return {
    commandList: [],
    add: function (command) {
      this.commandList.push(command)
    },
    execute: function () {
      for (let command of this.commandList) {
        command()
      }
    }
  }
};
